/**
 * Created by zl206 on 2016/11/5.
 */
var canvas=document.getElementById("canvas");
var cxt=canvas.getContext('2d');
var dtt=0;
var width=canvas.width;
var height=canvas.height;
var bgW=5*width;
var bgH=5*height;
var wX=(bgW-width)/2;
var wY=(bgH-height)/2;
var mX=wX+width/2;
var mY=wY+width/2;
var dW=width;
var dH=height;
var rate=1;


var heads=[];
var points;
var bgPoints;
var mysnake;
var othersnakes=[];
var spd=false;

var lastTime=Date.now();

var websocket;
var send=false;

document.body.onload=start;
function start() {
    canvas.onmousemove=function (e) {
        mX=e.offsetX;
        mY=e.offsetY;
    };
    document.body.onkeydown=function (e) {
        if(e.keyCode==32){
            spd=true;
            e.preventDefault();
        }
    };
    document.body.onkeyup=function (e) {
        if(e.keyCode==32){
            spd=false;
        }
    };
    init();
    run();
}

function init() {
    var srcs=["1.png","2.png","3.png","4.png","5.png","6.png","7.png"];
    for(var i = 0; i< srcs.length; ++i){
        heads[i]=new Image();
        heads[i].src="./heads/"+srcs[i];
    }
    websocket=new WebSocket("ws://"+location.host+"/snake");
    websocket.onclose=function(){
        console.log('xxxx');
    };
    websocket.onerror=function(ex){
        console.log(ex);
    };
    websocket.onmessage=function (msg) {
        var js=JSON.parse(msg.data);
        if(js.code=="you"){
            send=true;
            mysnake=js.snake;
        }else if(js.code=="data"){
            send=true;
            othersnakes=js.snake;
            points=js.dd;
            bgPoints=js.bgdd;
        }
    };
}
function sendForward() {
    if (!send)return;
    var angle=Math.atan2(mY-height/2,mX-width/2);
    var js={angle:angle,speedup:spd};
    websocket.send(JSON.stringify(js));
    send=false;
}

function run() {
    requestAnimationFrame(run);
    var now=Date.now();
    dtt=now-lastTime;
    lastTime=now;
    if (mysnake==null)return;
    cxt.clearRect(0,0,dW,dH);
    cxt.scale(1/rate,1/rate);
    cxt.save();
    setCenter();
    drawOtherSnakes(othersnakes);
    if(points!=null)
    drawPoints.call(points);
    if(bgPoints!=null){
        drawPoints.call(bgPoints,2);
    }
    bg();
    sendForward();
    cxt.restore();
}